package com.ruoyi.web.controller.teaching;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.teaching.domain.Option;
import com.ruoyi.teaching.domain.VettingRequest;
import com.ruoyi.teaching.domain.vo.PlatformQQuestionVO;
import com.ruoyi.teaching.domain.vo.PlatformUVirtualVO;
import com.ruoyi.teaching.service.PlatformUVirtualService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.ruoyi.web.controller.teaching.PlatformQQuestionController.validateMultipleChoiceAnswer;
import static com.ruoyi.web.controller.teaching.PlatformQQuestionController.validateSingleOrJudgeAnswer;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 王旭
 * @since 2024-06-29
 */
@RestController
@RequestMapping("/platform/virtual")
@Api(tags = "platform-虚拟仿真管理")
@Validated
public class PlatformUVirtualController {
    @Autowired
    private PlatformUVirtualService platformUVirtualService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询自己上传的虚拟仿真列表
     */
    @GetMapping("/listOwn")
//    @PreAuthorize("@ss.hasPermi('platform:virtual:listOwn')")
    @ApiOperation(value = "查询自己上传的虚拟仿真列表")
    public AjaxResult listOwn(Integer pageNum,Integer pageSize,Integer virtualType,Integer vettingStatus,String virtualName)
    {
        return platformUVirtualService.selectPlatformUVirtualListOwn(pageNum, pageSize, virtualType, vettingStatus, virtualName);
    }

    /**
     * 后台系统管理员查询虚拟仿真上传列表
     */
//    @PreAuthorize("@ss.hasPermi('platform:virtual:listOwn')")
    @GetMapping("/listSystemAdmin")
    @ApiOperation(value = "后台系统管理员查询虚拟仿真上传列表", notes = "后台系统管理员查询虚拟仿真上传列表")
    public AjaxResult listSystemAdmin(Integer pageNum,Integer pageSize,Integer virtualType,Integer vettingStatus,String virtualName)
    {
        return platformUVirtualService.selectPlatformUVirtualListSystemAdmin(pageNum, pageSize, virtualType, vettingStatus, virtualName);
    }

    /**
     * 用户查询已通过虚拟仿真上传列表
     */
//    @PreAuthorize("@ss.hasPermi('platform:virtual:listUser')")
    @GetMapping("/listUser")
    @ApiOperation(value = "用户查询已通过虚拟仿真上传列表", notes = "用户查询已通过虚拟仿真上传列表")
    public AjaxResult listUser(Integer pageNum,Integer pageSize,Integer virtualType,Integer professionalCategoryId,Integer professionalId,String virtualName,Integer sortord,Long softwareTagId)
    {
        return platformUVirtualService.selectPlatformUVirtualListUser(pageNum, pageSize, virtualType, professionalCategoryId, professionalId, virtualName,sortord,softwareTagId);
    }


    /**
     * 获取虚拟仿真详细信息
     */
//    @PreAuthorize("@ss.hasPermi('platform:virtual:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取虚拟仿真详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return platformUVirtualService.selectPlatformUVirtualById(id);
    }

    /**
     * 获取虚拟仿真的前五个热搜
     */
    @GetMapping("/hotSearch")
    @ApiOperation(value = "获取虚拟仿真的前五个热搜", notes = "获取虚拟仿真的前五个热搜")
    public AjaxResult getHotSearch(){
        return platformUVirtualService.selectHotSearch();
    }

    /**
     * 新增虚拟仿真
     */
//    @PreAuthorize("@ss.hasPermi('platform:virtual:add')")
    @Log(title = "【新增虚拟仿真】", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增虚拟仿真", notes = "新增虚拟仿真")
    @PostMapping
    public AjaxResult add(@Valid @RequestBody PlatformUVirtualVO platformUVirtualVO)
    {
        return platformUVirtualService.insertPlatformUVirtual(platformUVirtualVO);
    }

    /**
     * 上传虚拟仿真题库
     */
    @Log(title = "【上传虚拟仿真题库】", businessType = BusinessType.INSERT)
    @ApiOperation(value = "上传虚拟仿真题库", notes = "上传虚拟仿真题库")
    @PostMapping("/upload")
    public AjaxResult add(@RequestBody List<PlatformQQuestionVO> platformQQuestionDTOs) throws IOException{
        List<String> errorMessages = validatePlatformQQuestions(platformQQuestionDTOs);
        if(platformQQuestionDTOs.size() != 20){
            errorMessages.add("上传的题库数量不等于20");
        }
        if (!errorMessages.isEmpty()) {
            return AjaxResult.error(String.join(", ", errorMessages));
        }
        String urlBefore = serverConfig.getUrl();
        return platformUVirtualService.insertPlatformUVirtualQuestions(platformQQuestionDTOs,urlBefore);
    }

    private List<String> validatePlatformQQuestions(List<PlatformQQuestionVO> platformQQuestionDTOs) {
        List<String> errorMessages = new ArrayList<>();
        for (PlatformQQuestionVO question : platformQQuestionDTOs) {
            errorMessages.addAll(validatePlatformQQuestion(question));
        }
        return errorMessages;
    }

    private Collection<String> validatePlatformQQuestion(PlatformQQuestionVO question) {
        List<String> errorMessages = new ArrayList<>();
        String questionName = question.getQuestionName();

        // 验证题目是否为空以及长度是否在0-100之间
        if (questionName == null || questionName.isEmpty()) {
            errorMessages.add("有空题目，请检查后重试");
        } else if (questionName.length() > 100) {
            errorMessages.add("题目：" + questionName + " 的长度不能超过100个字符");
        }
        if (question.getQuestionType() == null) {
            errorMessages.add("题目：" + questionName + " 的题型不能为空");
        } else if (question.getQuestionType() < 0 || question.getQuestionType() > 2) {
            errorMessages.add("题目：" + questionName + " 的题型无效");
        }
        // 如果题型为单选题、多选题、判断题，检查选项内容和图片
        if (question.getQuestionType() != null) {
            if (question.getQuestionType() == 0 || question.getQuestionType() == 1 || question.getQuestionType() == 2) {
                for (Option option : question.getOptions()) {
                    if ((option.getContent() == null || option.getContent().isEmpty())) {
                        errorMessages.add("题目：" + questionName + " 的选项 " + option.getOption() + " 的内容不能为空");
                    }
                    if (option.getContent() != null && option.getContent().length() > 50) {
                        errorMessages.add("题目：" + questionName + " 的选项 " + option.getOption() + " 的内容长度不能超过50个字符");
                    }
                }
            }
        }
        // 根据题型验证答案
        if (question.getQuestionType() != null) {
            if (question.getQuestionType() == 1) { // 多选题
                validateMultipleChoiceAnswer(question, errorMessages);
            }  else if(question.getQuestionType() == 0 || question.getQuestionType() == 2){ // 单选题或判断题
                validateSingleOrJudgeAnswer(question, errorMessages);
            }
        }
        return errorMessages;
    }

    /**
     * 管理员审批虚拟仿真是否通过
     */
//    @PreAuthorize("@ss.hasPermi('platform:virtual:vetting')")
    @Log(title = "【管理员审批虚拟仿真是否通过】", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "管理员审批虚拟仿真是否通过", notes = "管理员审批虚拟仿真是否通过")
    @PutMapping(value = "/vetting")
    public AjaxResult vetting(@Valid @RequestBody VettingRequest vettingRequest)
    {
        if(vettingRequest.getVettingStatus() == 2 && null == vettingRequest.getNotPassingType()){
            return AjaxResult.error("请选择不通过的理由");
        }
        return platformUVirtualService.updatePlatformUVirtualVetting(vettingRequest);
    }

    /**
     * 删除虚拟仿真
     */
//    @PreAuthorize("@ss.hasPermi('platform:virtual:remove')")
    @Log(title = "【删除虚拟仿真】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除虚拟仿真", notes = "删除虚拟仿真")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return platformUVirtualService.deletePlatformUVirtualByIds(ids);
    }

    /**
     * 增加虚拟仿真浏览量
     */
    @GetMapping("/addView/{id}")
    @ApiOperation(value = "增加虚拟仿真浏览量", notes = "增加虚拟仿真浏览量")
    public void addView(@PathVariable Long id){
        platformUVirtualService.addView(id);
    }
}

